// XOverPtOp
// Copyright (c) 1998-2003 Matthew Faupel
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Library Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Library Public License for more details.
//
// You should have received a copy of the GNU Library Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
// 
// This Java class is inspired in part by the GAGS C++ library which I
// presume to be copyright J. J. Merelo <jmerelo@kal-el.ugr.es>.

package com.micropraxis.gajit;

import java.util.ArrayList;

import com.micropraxis.util.RandomInt;

/**
 * A class that represents a binary genetic operator that performs an n point
 * crossover between two chromosomes. Gene boundaries are not respected.
 * 
 * @author gajit@micropraxis.com
 * @version 0.2
 */
public class XOverPtOp extends GenOp
{
	protected int[] xOverPts;

	public XOverPtOp(int numPts)
	{
		super(true);

		// Two extra elements to hold zero at the beginning and max length
		// at the end to provide fixed endpoints to the crossovers.

		xOverPts = new int[((numPts >= 1) ? numPts : 1) + 2];
		xOverPts[0] = 0;
	}

	public Chrom apply(Chrom chrom1, Chrom chrom2)
	{
		ArrayList<ArrayList<Integer>> bs = new ArrayList<ArrayList<Integer>>(2);
		
		int minSize = chrom1.size();
		
		if(chrom2.size() < minSize)
			minSize = chrom2.size();
		
		for(int i = 1; i < minSize; i = i + 2)
		{
			
			bs.add(chrom1.get(i));
			bs.add(chrom1.get(i + 1));
			
			chrom1.set(i, chrom2.get(i));
			chrom1.set(i + 1, chrom2.get(i + 1));
			
			chrom2.set(i, bs.get(0));
			chrom2.set(i + 1, bs.get(1));
		}

		return (Chrom) chrom1;
	}

	public Chrom applyAt(int index, Chrom chrom1, Chrom chrom2)
	{
		return apply(chrom1, chrom2);
	}
}
